<?php

declare(strict_types=1);

namespace App\Controller\MchApi;
use App\Exception\XZXValidationException;
use App\Middleware\MchApi\MchJWTAuthMiddleware;
use App\Service\RateCustomizedService;
use App\Utils\CustomUtils;
use Hyperf\Contract\TranslatorInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

/**
 * Class RateCustomizedController
 * @package App\Controller
 * @Controller(prefix="/mch/api/rateCustomized")
 */
class RateCustomizedController extends MchBaseController
{

    /**
     * @Inject
     * @var TranslatorInterface
     */
    private $translator;
    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var RateCustomizedService
     */
    protected $RateCustomizedService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    private function setLocale () {
        if ($this->request->header('locale') == 'en') {
            $this->translator->setLocale('en');
        }
    }

    /**
     * 查询汇率
     * @PostMapping(path = "getTransRateAndAmount")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function getTransRateAndAmount(RequestInterface $request) {

        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'sourceCurrency' => 'required|alpha',
                'targetCurrency' => 'required|alpha',
                'amount' => 'required',
                'type' => 'required',
                'mchId' => 'required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }
        $param = $request->all();
        CustomUtils::xzxDebug($param);

        return $this->RateCustomizedService->getTransRateAndAmount($param);
    }
   
}